package com.web.d07.Cookie.练习;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/*
    cookie工具类，判断cookie中是否含有name：history
 */
public class CookieUtils {

    /**
     *
     * @param request
     * @param history  cookie中的name
     * @return   返回的是名为 history 的cookie
     */
    public static Cookie getCookies(HttpServletRequest request, String history) {
        //1、获取浏览器的cookie
        Cookie[] cookies = request.getCookies();
        //2、cookies可能为null，遍历的话会出现异常，为了避免需要先判断
        if (cookies != null) {
            //3、说明浏览器有cookie，获取name是history的cookie
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                if (cookieName.equals(history)) {
                    //找到了history对应的cookie,将它返回
                    return cookie;
                }
            }
        }
        return null;
    }
}
